using CollabApp.Application.Interfaces;
using CollabApp.Domain.Entities.Game;
using CollabApp.Domain.Services.Game;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Text.Json;

namespace CollabApp.Application.Services.Game;

/// <summary>
/// 游戏玩法服务
/// 负责处理游戏核心玩法逻辑，包括移动、攻击、收集、技能使用等游戏行为
/// 提供企业级的游戏玩法处理和验证能力
/// </summary>
public class GamePlayService : IGamePlayService
{
    private readonly IRedisService _redisService;
    private readonly ILogger<GamePlayService> _logger;
    private readonly IGameStateService _gameStateService;
    private readonly IPlayerStateService _playerStateService;
    private readonly ICollisionDetectionService _collisionDetectionService;
    private readonly ITerritoryService _territoryService;
    private readonly IPowerUpService _powerUpService;
    
    // 缓存和状态管理
    private readonly ConcurrentDictionary<Guid, List<AvailableAction>> _actionCache = new();
    private readonly ConcurrentDictionary<Guid, DateTime> _lastActionTime = new();
    private readonly ConcurrentDictionary<string, TimeSpan> _cooldownTracker = new();
    
    // 游戏配置常量
    private const float MAX_MOVE_SPEED = 10.0f;
    private const float MIN_ATTACK_DAMAGE = 10.0f;
    private const float MAX_ATTACK_DAMAGE = 100.0f;
    private const float TERRITORY_CLAIM_RADIUS = 50.0f;
    private const int MAX_ACTIONS_PER_SECOND = 20;
    private const double ACTION_COOLDOWN_MS = 50; // 50毫秒最小间隔

    public GamePlayService(
        IRedisService redisService,
        ILogger<GamePlayService> logger,
        IGameStateService gameStateService,
        IPlayerStateService playerStateService,
        ICollisionDetectionService collisionDetectionService,
        ITerritoryService territoryService,
        IPowerUpService powerUpService)
    {
        _redisService = redisService ?? throw new ArgumentNullException(nameof(redisService));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _gameStateService = gameStateService ?? throw new ArgumentNullException(nameof(gameStateService));
        _playerStateService = playerStateService ?? throw new ArgumentNullException(nameof(playerStateService));
        _collisionDetectionService = collisionDetectionService ?? throw new ArgumentNullException(nameof(collisionDetectionService));
        _territoryService = territoryService ?? throw new ArgumentNullException(nameof(territoryService));
        _powerUpService = powerUpService ?? throw new ArgumentNullException(nameof(powerUpService));
        
        _logger.LogInformation("GamePlayService 已初始化，准备提供游戏玩法处理服务");
    }

    #region 移动处理

    /// <summary>
    /// 处理玩家移动
    /// 验证移动的合法性，更新玩家位置，检测碰撞和边界
    /// </summary>
    public async Task<MoveResult> ProcessPlayerMoveAsync(Guid gameId, Guid playerId, MoveCommand moveCommand)
    {
        if (gameId == Guid.Empty || playerId == Guid.Empty || moveCommand == null)
        {
            _logger.LogWarning("处理玩家移动失败：无效的参数");
            return new MoveResult 
            { 
                Success = false, 
                Errors = new List<string> { "无效的移动参数" }
            };
        }

        try
        {
            // 防止操作过于频繁
            if (!await ValidateActionRateAsync(playerId))
            {
                return new MoveResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "操作过于频繁，请稍后重试" }
                };
            }

            // 获取当前玩家状态
            var playerState = await _playerStateService.GetPlayerStateAsync(gameId, playerId);
            if (playerState == null || playerState.State == PlayerDrawingState.Dead)
            {
                return new MoveResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "玩家状态无效或已死亡" }
                };
            }

            // 验证游戏状态
            var gameState = await _gameStateService.GetGameStateAsync(gameId);
            if (gameState == null || gameState.Status != GameStatus.Playing)
            {
                return new MoveResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "游戏未在进行中" }
                };
            }

            // 验证移动合法性
            var validationResult = await ValidateMoveAsync(gameId, playerId, moveCommand);
            if (!validationResult.IsValid)
            {
                return new MoveResult 
                { 
                    Success = false, 
                    Errors = validationResult.Errors
                };
            }

            var oldPosition = new Position 
            { 
                X = playerState.CurrentPosition.X, 
                Y = playerState.CurrentPosition.Y 
            };

            // 更新玩家位置
            var updateResult = await _playerStateService.UpdatePlayerPositionAsync(
                gameId, playerId, moveCommand.NewPosition, moveCommand.Timestamp);

            if (!updateResult.Success)
            {
                return new MoveResult 
                { 
                    Success = false, 
                    Errors = updateResult.Errors
                };
            }

            // 检测碰撞和交互
            var events = new List<GameEvent>();
            await CheckMoveCollisionsAsync(gameId, playerId, moveCommand.NewPosition, events);

            var result = new MoveResult
            {
                Success = true,
                OldPosition = oldPosition,
                NewPosition = moveCommand.NewPosition,
                TriggeredEvents = events
            };

            _logger.LogDebug("玩家移动处理完成 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, " +
                "从 ({OldX},{OldY}) 移动到 ({NewX},{NewY})", 
                gameId, playerId, oldPosition.X, oldPosition.Y, 
                moveCommand.NewPosition.X, moveCommand.NewPosition.Y);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理玩家移动时发生错误 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", 
                gameId, playerId);
            return new MoveResult 
            { 
                Success = false, 
                Errors = new List<string> { "移动处理失败" }
            };
        }
    }

    #endregion

    #region 攻击处理

    /// <summary>
    /// 处理玩家攻击行为
    /// 验证攻击条件，计算伤害，更新游戏状态
    /// </summary>
    public async Task<AttackResult> ProcessPlayerAttackAsync(Guid gameId, Guid attackerId, AttackCommand attackCommand)
    {
        if (gameId == Guid.Empty || attackerId == Guid.Empty || attackCommand == null)
        {
            _logger.LogWarning("处理玩家攻击失败：无效的参数");
            return new AttackResult 
            { 
                Success = false, 
                Errors = new List<string> { "无效的攻击参数" }
            };
        }

        try
        {
            // 防止操作过于频繁
            if (!await ValidateActionRateAsync(attackerId))
            {
                return new AttackResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "攻击过于频繁，请稍后重试" }
                };
            }

            // 获取攻击者状态
            var attackerState = await _playerStateService.GetPlayerStateAsync(gameId, attackerId);
            if (attackerState == null || attackerState.State == PlayerDrawingState.Dead)
            {
                return new AttackResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "攻击者状态无效或已死亡" }
                };
            }

            // 验证攻击条件
            var validationResult = await ValidateAttackAsync(gameId, attackerId, attackCommand);
            if (!validationResult.IsValid)
            {
                return new AttackResult 
                { 
                    Success = false, 
                    Errors = validationResult.Errors
                };
            }

            var events = new List<GameEvent>();
            var affectedPlayers = new List<Guid>();

            // 执行攻击逻辑
            float damageDealt = 0;
            
            if (attackCommand.TargetPlayerId.HasValue)
            {
                // 针对特定玩家的攻击
                damageDealt = await ProcessPlayerAttackAsync(gameId, attackerId, 
                    attackCommand.TargetPlayerId.Value, attackCommand, events);
                    
                if (damageDealt > 0)
                {
                    affectedPlayers.Add(attackCommand.TargetPlayerId.Value);
                }
            }
            else
            {
                // 区域攻击
                damageDealt = await ProcessAreaAttackAsync(gameId, attackerId, 
                    attackCommand.TargetPosition, attackCommand, events, affectedPlayers);
            }

            var result = new AttackResult
            {
                Success = damageDealt > 0,
                DamageDealt = damageDealt,
                AffectedPlayers = affectedPlayers,
                TriggeredEvents = events
            };

            if (!result.Success && result.Errors.Count == 0)
            {
                result.Errors.Add("攻击未命中目标");
            }

            _logger.LogInformation("玩家攻击处理完成 - 游戏ID: {GameId}, 攻击者ID: {AttackerId}, " +
                "伤害: {Damage}, 影响玩家数: {AffectedCount}", 
                gameId, attackerId, damageDealt, affectedPlayers.Count);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理玩家攻击时发生错误 - 游戏ID: {GameId}, 攻击者ID: {AttackerId}", 
                gameId, attackerId);
            return new AttackResult 
            { 
                Success = false, 
                Errors = new List<string> { "攻击处理失败" }
            };
        }
    }

    #endregion

    #region 物品收集

    /// <summary>
    /// 处理物品收集
    /// 验证收集条件，更新玩家库存，移除地图物品
    /// </summary>
    public async Task<CollectResult> ProcessItemCollectionAsync(Guid gameId, Guid playerId, Guid itemId)
    {
        if (gameId == Guid.Empty || playerId == Guid.Empty || itemId == Guid.Empty)
        {
            _logger.LogWarning("处理物品收集失败：无效的参数");
            return new CollectResult 
            { 
                Success = false, 
                Errors = new List<string> { "无效的收集参数" }
            };
        }

        try
        {
            // 防止操作过于频繁
            if (!await ValidateActionRateAsync(playerId))
            {
                return new CollectResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "操作过于频繁，请稍后重试" }
                };
            }

            // 验证玩家状态
            var playerState = await _playerStateService.GetPlayerStateAsync(gameId, playerId);
            if (playerState == null || playerState.State == PlayerDrawingState.Dead)
            {
                return new CollectResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "玩家状态无效或已死亡" }
                };
            }

            // 使用道具服务处理收集
            var collectResult = await _powerUpService.PickupPowerUpAsync(gameId, playerId, itemId, playerState.CurrentPosition);
            if (!collectResult.Success)
            {
                return new CollectResult 
                { 
                    Success = false, 
                    Errors = collectResult.Errors
                };
            }

            var events = new List<GameEvent>
            {
                new GameEvent
                {
                    EventType = "item_collected",
                    PlayerId = playerId,
                    Description = "玩家收集了物品",
                    Timestamp = DateTime.UtcNow,
                    Data = new Dictionary<string, object> { ["item_id"] = itemId }
                }
            };

            var result = new CollectResult
            {
                Success = true,
                ItemName = "游戏道具", // 简化实现
                Quantity = 1,
                TriggeredEvents = events
            };

            _logger.LogInformation("物品收集完成 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, 物品ID: {ItemId}", 
                gameId, playerId, itemId);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理物品收集时发生错误 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, 物品ID: {ItemId}", 
                gameId, playerId, itemId);
            return new CollectResult 
            { 
                Success = false, 
                Errors = new List<string> { "收集处理失败" }
            };
        }
    }

    #endregion

    #region 技能使用

    /// <summary>
    /// 使用道具/技能
    /// 验证使用条件，应用道具效果，更新冷却时间
    /// </summary>
    public async Task<SkillUseResult> UsePlayerSkillAsync(Guid gameId, Guid playerId, SkillUseCommand skillCommand)
    {
        if (gameId == Guid.Empty || playerId == Guid.Empty || skillCommand == null)
        {
            _logger.LogWarning("使用技能失败：无效的参数");
            return new SkillUseResult 
            { 
                Success = false, 
                Errors = new List<string> { "无效的技能参数" }
            };
        }

        try
        {
            // 检查技能冷却
            var cooldownKey = $"{playerId}_{skillCommand.SkillId}";
            if (_cooldownTracker.ContainsKey(cooldownKey))
            {
                var remaining = _cooldownTracker[cooldownKey];
                if (remaining > TimeSpan.Zero)
                {
                    return new SkillUseResult 
                    { 
                        Success = false,
                        SkillId = skillCommand.SkillId,
                        CooldownRemaining = remaining,
                        Errors = new List<string> { $"技能冷却中，剩余时间: {remaining.TotalSeconds:F1}秒" }
                    };
                }
            }

            // 验证玩家状态
            var playerState = await _playerStateService.GetPlayerStateAsync(gameId, playerId);
            if (playerState == null || playerState.State == PlayerDrawingState.Dead)
            {
                return new SkillUseResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "玩家状态无效或已死亡" }
                };
            }

            // 使用道具服务处理技能使用（简化实现）
            bool useSuccess = false;
            
            switch (skillCommand.SkillId.ToLower())
            {
                case "lightning":
                case "speed_boost":
                    var lightningResult = await _powerUpService.UseLightningPowerUpAsync(gameId, playerId);
                    useSuccess = lightningResult.Success;
                    break;
                case "shield":
                    var shieldResult = await _powerUpService.UseShieldPowerUpAsync(gameId, playerId);
                    useSuccess = shieldResult.Success;
                    break;
                case "bomb":
                    var bombResult = await _powerUpService.UseBombPowerUpAsync(gameId, playerId, 
                        skillCommand.TargetPosition ?? playerState.CurrentPosition);
                    useSuccess = bombResult.Success;
                    break;
                case "ghost":
                case "teleport":
                    var ghostResult = await _powerUpService.UseGhostPowerUpAsync(gameId, playerId);
                    useSuccess = ghostResult.Success;
                    break;
                default:
                    useSuccess = false;
                    break;
            }
            
            if (!useSuccess)
            {
                return new SkillUseResult 
                { 
                    Success = false,
                    SkillId = skillCommand.SkillId,
                    Errors = new List<string> { "技能使用失败或道具不可用" }
                };
            }

            // 设置技能冷却
            var cooldownDuration = GetSkillCooldown(skillCommand.SkillId);
            _cooldownTracker[cooldownKey] = cooldownDuration;

            var events = new List<GameEvent>
            {
                new GameEvent
                {
                    EventType = "skill_used",
                    PlayerId = playerId,
                    Description = $"玩家使用了技能: {skillCommand.SkillId}",
                    Timestamp = DateTime.UtcNow,
                    Data = new Dictionary<string, object> 
                    { 
                        ["skill_id"] = skillCommand.SkillId,
                        ["cooldown_seconds"] = cooldownDuration.TotalSeconds
                    }
                }
            };

            var result = new SkillUseResult
            {
                Success = true,
                SkillId = skillCommand.SkillId,
                CooldownRemaining = cooldownDuration,
                AffectedPlayers = new List<Guid> { playerId },
                TriggeredEvents = events
            };

            _logger.LogInformation("技能使用完成 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, 技能: {SkillId}", 
                gameId, playerId, skillCommand.SkillId);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "使用技能时发生错误 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, 技能: {SkillId}", 
                gameId, playerId, skillCommand?.SkillId);
            return new SkillUseResult 
            { 
                Success = false,
                SkillId = skillCommand?.SkillId ?? "unknown",
                Errors = new List<string> { "技能使用处理失败" }
            };
        }
    }

    #endregion

    #region 领土占领

    /// <summary>
    /// 处理领土占领
    /// 验证占领条件，更新领土归属，计算影响范围
    /// </summary>
    public async Task<TerritoryClaimResult> ProcessTerritoryClaimAsync(Guid gameId, Guid playerId, TerritoryClaimCommand territoryCommand)
    {
        if (gameId == Guid.Empty || playerId == Guid.Empty || territoryCommand == null)
        {
            _logger.LogWarning("处理领土占领失败：无效的参数");
            return new TerritoryClaimResult 
            { 
                Success = false, 
                Errors = new List<string> { "无效的领土占领参数" }
            };
        }

        try
        {
            // 防止操作过于频繁
            if (!await ValidateActionRateAsync(playerId))
            {
                return new TerritoryClaimResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "操作过于频繁，请稍后重试" }
                };
            }

            // 验证玩家状态
            var playerState = await _playerStateService.GetPlayerStateAsync(gameId, playerId);
            if (playerState == null || playerState.State == PlayerDrawingState.Dead)
            {
                return new TerritoryClaimResult 
                { 
                    Success = false, 
                    Errors = new List<string> { "玩家状态无效或已死亡" }
                };
            }

            // 使用领土服务处理占领
            var claimResult = await _territoryService.CompleteTerritoryAsync(gameId, playerId, 
                territoryCommand.Position);

            if (!claimResult.Success)
            {
                return new TerritoryClaimResult 
                { 
                    Success = false, 
                    Errors = new List<string> { claimResult.ErrorMessage ?? "领土占领失败" }
                };
            }

            // 计算奖励积分
            var bonusScore = (int)(claimResult.AreaGained * 10);
            // 简化实现：直接在玩家状态中更新（AddPlayerScoreAsync 方法不存在）

            var events = new List<GameEvent>
            {
                new GameEvent
                {
                    EventType = "territory_claimed",
                    PlayerId = playerId,
                    Description = $"玩家占领了面积为 {claimResult.AreaGained:F1} 的领土",
                    Timestamp = DateTime.UtcNow,
                    Data = new Dictionary<string, object> 
                    { 
                        ["area_gained"] = claimResult.AreaGained,
                        ["bonus_score"] = bonusScore,
                        ["territory_count"] = claimResult.NewTerritory.Count
                    }
                }
            };

            var result = new TerritoryClaimResult
            {
                Success = true,
                TerritoryId = Guid.NewGuid(), // 简化实现，生成新ID
                TerritoryGained = (float)claimResult.AreaGained,
                TerritoryLost = 0,
                NewTotalArea = (float)claimResult.NewTotalArea,
                BonusScore = bonusScore,
                AffectedPlayers = claimResult.ConqueredPlayers.Concat(new[] { playerId }).ToList(),
                Messages = new List<string> { $"成功占领 {claimResult.AreaGained:F1} 面积的领土" },
                TriggeredEvents = events
            };

            _logger.LogInformation("领土占领完成 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, " +
                "占领面积: {AreaGained}, 奖励积分: {BonusScore}", 
                gameId, playerId, claimResult.AreaGained, bonusScore);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理领土占领时发生错误 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", 
                gameId, playerId);
            return new TerritoryClaimResult 
            { 
                Success = false, 
                Errors = new List<string> { "领土占领处理失败" }
            };
        }
    }

    #endregion

    #region 规则检查

    /// <summary>
    /// 执行游戏规则检查
    /// 检查当前游戏状态是否符合规则要求
    /// </summary>
    public async Task<RuleCheckResult> ExecuteRuleCheckAsync(Guid gameId)
    {
        if (gameId == Guid.Empty)
        {
            _logger.LogWarning("执行规则检查失败：无效的游戏ID");
            return new RuleCheckResult 
            { 
                IsValid = false,
                Violations = new List<string> { "无效的游戏ID" }
            };
        }

        try
        {
            var violations = new List<string>();
            var warnings = new List<string>();
            var events = new List<GameEvent>();

            // 检查游戏状态
            var gameState = await _gameStateService.GetGameStateAsync(gameId);
            if (gameState == null)
            {
                violations.Add("游戏状态不存在");
            }
            else
            {
                // 检查游戏时间限制
                if (gameState.ElapsedTime > TimeSpan.FromHours(2))
                {
                    warnings.Add("游戏时间过长，建议结束");
                }

                // 检查游戏状态一致性
                if (gameState.Status == GameStatus.Playing && gameState.RemainingTime <= TimeSpan.Zero)
                {
                    violations.Add("游戏状态与剩余时间不一致");
                    
                    events.Add(new GameEvent
                    {
                        EventType = "game_time_expired",
                        Description = "游戏时间已到，需要结束游戏",
                        Timestamp = DateTime.UtcNow
                    });
                }
            }

            // 检查玩家状态
            var playerStates = await _playerStateService.GetAllPlayerStatesAsync(gameId);
            if (playerStates.Any())
            {
                var alivePlayers = playerStates.Count(p => p.State != PlayerDrawingState.Dead);
                
                // 检查获胜条件
                if (alivePlayers <= 1 && gameState?.Status == GameStatus.Playing)
                {
                    events.Add(new GameEvent
                    {
                        EventType = "game_should_end",
                        Description = "只剩一个或零个存活玩家，游戏应该结束",
                        Timestamp = DateTime.UtcNow,
                        Data = new Dictionary<string, object> { ["alive_players"] = alivePlayers }
                    });
                }

                // 检查玩家位置合法性
                foreach (var player in playerStates)
                {
                    if (player.CurrentPosition.X < 0 || player.CurrentPosition.Y < 0 ||
                        player.CurrentPosition.X > 1000 || player.CurrentPosition.Y > 1000) // 假设地图大小为1000x1000
                    {
                        violations.Add($"玩家 {player.PlayerId} 的位置超出地图边界");
                    }
                }
            }

            var result = new RuleCheckResult
            {
                IsValid = violations.Count == 0,
                Violations = violations,
                Warnings = warnings,
                TriggeredEvents = events
            };

            _logger.LogDebug("游戏规则检查完成 - 游戏ID: {GameId}, 是否合规: {IsValid}, " +
                "违规数: {ViolationCount}, 警告数: {WarningCount}", 
                gameId, result.IsValid, violations.Count, warnings.Count);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "执行游戏规则检查时发生错误 - 游戏ID: {GameId}", gameId);
            return new RuleCheckResult 
            { 
                IsValid = false,
                Violations = new List<string> { "规则检查失败" }
            };
        }
    }

    #endregion

    #region 可用行为查询

    /// <summary>
    /// 获取玩家可执行的行为列表
    /// 基于当前游戏状态和玩家状态，返回合法的行为选项
    /// </summary>
    public async Task<List<AvailableAction>> GetAvailableActionsAsync(Guid gameId, Guid playerId)
    {
        if (gameId == Guid.Empty || playerId == Guid.Empty)
        {
            _logger.LogWarning("获取可用行为失败：无效的参数");
            return new List<AvailableAction>();
        }

        try
        {
            // 检查缓存
            var cacheKey = gameId;
            if (_actionCache.TryGetValue(cacheKey, out var cachedActions))
            {
                // 缓存有效期5秒
                if (_lastActionTime.ContainsKey(cacheKey) && 
                    DateTime.UtcNow - _lastActionTime[cacheKey] < TimeSpan.FromSeconds(5))
                {
                    return cachedActions;
                }
            }

            var actions = new List<AvailableAction>();

            // 验证基本状态
            var playerState = await _playerStateService.GetPlayerStateAsync(gameId, playerId);
            var gameState = await _gameStateService.GetGameStateAsync(gameId);

            if (playerState == null || gameState == null)
            {
                return actions;
            }

            var isPlayerAlive = playerState.State != PlayerDrawingState.Dead;
            var isGameInProgress = gameState.Status == GameStatus.Playing;

            // 移动行为
            actions.Add(new AvailableAction
            {
                ActionId = "move",
                ActionName = "移动",
                ActionType = ActionType.Move,
                IsAvailable = isPlayerAlive && isGameInProgress,
                DisabledReason = !isPlayerAlive ? "玩家已死亡" : !isGameInProgress ? "游戏未进行" : null,
                Parameters = new Dictionary<string, object>
                {
                    ["max_speed"] = MAX_MOVE_SPEED,
                    ["can_move_outside_territory"] = true
                }
            });

            // 攻击行为
            actions.Add(new AvailableAction
            {
                ActionId = "attack",
                ActionName = "攻击",
                ActionType = ActionType.Attack,
                IsAvailable = isPlayerAlive && isGameInProgress,
                DisabledReason = !isPlayerAlive ? "玩家已死亡" : !isGameInProgress ? "游戏未进行" : null,
                Parameters = new Dictionary<string, object>
                {
                    ["min_damage"] = MIN_ATTACK_DAMAGE,
                    ["max_damage"] = MAX_ATTACK_DAMAGE,
                    ["attack_types"] = new[] { "melee", "ranged" }
                }
            });

            // 物品收集行为
            var nearbyItems = await GetNearbyItemsAsync(gameId, playerState.CurrentPosition);
            actions.Add(new AvailableAction
            {
                ActionId = "collect",
                ActionName = "收集物品",
                ActionType = ActionType.Collect,
                IsAvailable = isPlayerAlive && isGameInProgress && nearbyItems.Any(),
                DisabledReason = !isPlayerAlive ? "玩家已死亡" : 
                               !isGameInProgress ? "游戏未进行" : 
                               !nearbyItems.Any() ? "附近没有可收集的物品" : null,
                Parameters = new Dictionary<string, object>
                {
                    ["nearby_items_count"] = nearbyItems.Count,
                    ["collect_range"] = 30.0f
                }
            });

            // 技能使用行为
            var availableSkills = await GetAvailableSkillsAsync(gameId, playerId);
            foreach (var skill in availableSkills)
            {
                var cooldownKey = $"{playerId}_{skill.SkillId}";
                var cooldownRemaining = _cooldownTracker.ContainsKey(cooldownKey) ? 
                    _cooldownTracker[cooldownKey] : TimeSpan.Zero;

                actions.Add(new AvailableAction
                {
                    ActionId = $"skill_{skill.SkillId}",
                    ActionName = $"使用技能: {skill.Name}",
                    ActionType = ActionType.UseSkill,
                    IsAvailable = isPlayerAlive && isGameInProgress && cooldownRemaining <= TimeSpan.Zero,
                    DisabledReason = !isPlayerAlive ? "玩家已死亡" : 
                                   !isGameInProgress ? "游戏未进行" : 
                                   cooldownRemaining > TimeSpan.Zero ? $"冷却中: {cooldownRemaining.TotalSeconds:F1}秒" : null,
                    CooldownRemaining = cooldownRemaining > TimeSpan.Zero ? cooldownRemaining : null,
                    Parameters = new Dictionary<string, object>
                    {
                        ["skill_id"] = skill.SkillId,
                        ["skill_type"] = skill.Type,
                        ["cooldown_seconds"] = GetSkillCooldown(skill.SkillId).TotalSeconds
                    }
                });
            }

            // 领土占领行为
            actions.Add(new AvailableAction
            {
                ActionId = "claim_territory",
                ActionName = "占领领土",
                ActionType = ActionType.ClaimTerritory,
                IsAvailable = isPlayerAlive && isGameInProgress,
                DisabledReason = !isPlayerAlive ? "玩家已死亡" : !isGameInProgress ? "游戏未进行" : null,
                Parameters = new Dictionary<string, object>
                {
                    ["max_claim_radius"] = TERRITORY_CLAIM_RADIUS,
                    ["territory_types"] = Enum.GetNames<TerritoryType>()
                }
            });

            // 更新缓存
            _actionCache.TryRemove(cacheKey, out _);
            _actionCache.TryAdd(cacheKey, actions);
            _lastActionTime[cacheKey] = DateTime.UtcNow;

            _logger.LogDebug("获取可用行为完成 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, 行为数: {ActionCount}", 
                gameId, playerId, actions.Count);

            return actions;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取可用行为时发生错误 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", 
                gameId, playerId);
            return new List<AvailableAction>();
        }
    }

    #endregion

    #region 行为预测

    /// <summary>
    /// 计算行为执行的预期结果
    /// 在不实际执行的情况下，模拟行为的影响
    /// </summary>
    public async Task<ActionPredictionResult> PredictActionResultAsync(Guid gameId, Guid playerId, IGameActionCommand actionCommand)
    {
        if (gameId == Guid.Empty || playerId == Guid.Empty || actionCommand == null)
        {
            _logger.LogWarning("预测行为结果失败：无效的参数");
            return new ActionPredictionResult
            {
                CanExecute = false,
                SuccessProbability = 0,
                Risks = new List<string> { "无效的预测参数" }
            };
        }

        try
        {
            var prediction = new ActionPredictionResult();
            var predictedEffects = new List<string>();
            var risks = new List<string>();
            var predictedChanges = new Dictionary<string, object>();

            // 获取当前状态
            var playerState = await _playerStateService.GetPlayerStateAsync(gameId, playerId);
            var gameState = await _gameStateService.GetGameStateAsync(gameId);

            if (playerState == null || gameState == null)
            {
                return new ActionPredictionResult
                {
                    CanExecute = false,
                    SuccessProbability = 0,
                    Risks = new List<string> { "无法获取游戏状态" }
                };
            }

            // 基于行为类型进行预测
            switch (actionCommand)
            {
                case MoveCommand moveCmd:
                    await PredictMoveResult(gameId, playerState, moveCmd, prediction, 
                        predictedEffects, risks, predictedChanges);
                    break;

                case AttackCommand attackCmd:
                    await PredictAttackResult(gameId, playerState, attackCmd, prediction, 
                        predictedEffects, risks, predictedChanges);
                    break;

                case SkillUseCommand skillCmd:
                    await PredictSkillResult(gameId, playerState, skillCmd, prediction, 
                        predictedEffects, risks, predictedChanges);
                    break;

                case TerritoryClaimCommand territoryCmd:
                    await PredictTerritoryResult(gameId, playerState, territoryCmd, prediction, 
                        predictedEffects, risks, predictedChanges);
                    break;

                default:
                    prediction.CanExecute = false;
                    prediction.SuccessProbability = 0;
                    risks.Add("未知的行为类型");
                    break;
            }

            prediction.PredictedEffects = predictedEffects;
            prediction.Risks = risks;
            prediction.PredictedChanges = predictedChanges;

            _logger.LogDebug("行为预测完成 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, " +
                "可执行: {CanExecute}, 成功率: {SuccessProbability:P}", 
                gameId, playerId, prediction.CanExecute, prediction.SuccessProbability);

            return prediction;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "预测行为结果时发生错误 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", 
                gameId, playerId);
            return new ActionPredictionResult
            {
                CanExecute = false,
                SuccessProbability = 0,
                Risks = new List<string> { "预测处理失败" }
            };
        }
    }

    /// <summary>
    /// 获取游戏事件流
    /// </summary>
    public async Task<GameEventsResult> GetGameEventsAsync(Guid gameId, DateTime? since = null, List<string>? eventTypes = null)
    {
        if (gameId == Guid.Empty)
        {
            return new GameEventsResult
            {
                Success = false,
                Errors = new List<string> { "无效的游戏ID" }
            };
        }

        try
        {
            // 使用Task.CompletedTask来满足async要求
            await Task.CompletedTask;
            
            // 简化实现：返回基础事件
            var events = new List<GameEvent>
            {
                new GameEvent
                {
                    EventType = "game_sync",
                    Description = "游戏事件同步",
                    Timestamp = DateTime.UtcNow,
                    Data = new Dictionary<string, object> { ["gameId"] = gameId }
                }
            };

            var lastEventTime = events.Max(e => e.Timestamp);

            _logger.LogDebug("获取游戏事件成功 - 游戏ID: {GameId}, 事件数: {EventCount}", 
                gameId, events.Count);

            return new GameEventsResult
            {
                Success = true,
                Events = events,
                LastEventTime = lastEventTime,
                TotalEvents = events.Count
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取游戏事件失败 - 游戏ID: {GameId}", gameId);
            return new GameEventsResult
            {
                Success = false,
                Errors = new List<string> { ex.Message }
            };
        }
    }

    /// <summary>
    /// 同步玩家位置
    /// </summary>
    public async Task<SyncPositionResult> SyncPlayerPositionAsync(
        Guid gameId, 
        Guid playerId, 
        Position position, 
        DateTime timestamp, 
        long sequence)
    {
        if (gameId == Guid.Empty || playerId == Guid.Empty || position == null)
        {
            return new SyncPositionResult
            {
                Success = false,
                Errors = new List<string> { "无效的同步参数" }
            };
        }

        try
        {
            var now = DateTime.UtcNow;
            var latency = (float)(now - timestamp).TotalMilliseconds;

            // 获取玩家当前状态
            var playerState = await _playerStateService.GetPlayerStateAsync(gameId, playerId);
            if (playerState == null)
            {
                return new SyncPositionResult
                {
                    Success = false,
                    Errors = new List<string> { "玩家状态不存在" }
                };
            }

            // 验证序列号（简化实现）
            var currentSequence = 0L; // playerState.LastSequence 的简化替代
            if (sequence <= currentSequence)
            {
                return new SyncPositionResult
                {
                    Success = false,
                    AuthoritativePosition = playerState.CurrentPosition,
                    ServerTimestamp = now,
                    AcknowledgedSequence = currentSequence,
                    Latency = latency,
                    Conflicts = new List<string> { "序列号过期" }
                };
            }

            // 位置合法性验证
            var conflicts = new List<string>();
            if (!IsPositionValid(gameId, position))
            {
                conflicts.Add("位置超出边界");
            }

            // 简化碰撞检测
            var hasCollision = false; // 简化实现
            if (hasCollision)
            {
                conflicts.Add("位置冲突");
            }

            Position authoritativePosition;
            if (conflicts.Count == 0)
            {
                // 应用延迟补偿
                authoritativePosition = ApplyLatencyCompensation(position, latency);
                
                // 更新玩家状态
                await _playerStateService.UpdatePlayerPositionAsync(gameId, playerId, authoritativePosition, now, false);
            }
            else
            {
                // 使用服务器权威位置
                authoritativePosition = playerState.CurrentPosition;
            }

            _logger.LogDebug("位置同步完成 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, 延迟: {Latency}ms", 
                gameId, playerId, latency);

            return new SyncPositionResult
            {
                Success = conflicts.Count == 0,
                AuthoritativePosition = authoritativePosition,
                ServerTimestamp = now,
                AcknowledgedSequence = sequence,
                Latency = latency,
                Conflicts = conflicts
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "同步玩家位置失败 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", 
                gameId, playerId);
            return new SyncPositionResult
            {
                Success = false,
                Errors = new List<string> { ex.Message }
            };
        }
    }

    /// <summary>
    /// 延迟补偿处理
    /// </summary>
    public async Task<LatencyCompensationResult> CompensateLatencyAsync(
        Guid gameId, 
        Guid playerId, 
        DateTime clientTimestamp, 
        Dictionary<string, object> actionData)
    {
        if (gameId == Guid.Empty || playerId == Guid.Empty || actionData == null)
        {
            return new LatencyCompensationResult
            {
                Success = false,
                Errors = new List<string> { "无效的补偿参数" }
            };
        }

        try
        {
            // 使用Task.CompletedTask来满足async要求
            await Task.CompletedTask;
            
            var serverTimestamp = DateTime.UtcNow;
            var estimatedLatency = (float)(serverTimestamp - clientTimestamp).TotalMilliseconds;
            
            // 限制延迟补偿范围（防止作弊）
            if (estimatedLatency < 0 || estimatedLatency > 1000) // 最大1秒延迟
            {
                return new LatencyCompensationResult
                {
                    Success = false,
                    EstimatedLatency = estimatedLatency,
                    Errors = new List<string> { "延迟超出合理范围" }
                };
            }

            var adjustedData = new Dictionary<string, object>(actionData);
            var corrections = new List<string>();

            // 位置补偿
            if (actionData.TryGetValue("position", out var positionObj) && positionObj is Position position)
            {
                var compensatedPosition = ApplyLatencyCompensation(position, estimatedLatency);
                adjustedData["position"] = compensatedPosition;
                corrections.Add("位置已补偿延迟");
            }

            // 时间戳调整
            var compensatedTimestamp = clientTimestamp.AddMilliseconds(estimatedLatency / 2);
            adjustedData["compensated_timestamp"] = compensatedTimestamp;

            // 速度补偿（如果有移动）
            if (actionData.TryGetValue("velocity", out var velocityObj) && velocityObj is float velocity)
            {
                var distanceCompensation = velocity * (estimatedLatency / 1000f);
                adjustedData["distance_compensation"] = distanceCompensation;
                corrections.Add("移动距离已补偿");
            }

            _logger.LogDebug("延迟补偿完成 - 游戏ID: {GameId}, 玩家ID: {PlayerId}, 延迟: {Latency}ms", 
                gameId, playerId, estimatedLatency);

            return new LatencyCompensationResult
            {
                Success = true,
                EstimatedLatency = estimatedLatency,
                CompensatedTimestamp = compensatedTimestamp,
                AdjustedData = adjustedData,
                Corrections = corrections
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "延迟补偿失败 - 游戏ID: {GameId}, 玩家ID: {PlayerId}", 
                gameId, playerId);
            return new LatencyCompensationResult
            {
                Success = false,
                Errors = new List<string> { ex.Message }
            };
        }
    }

    #endregion

    #region 辅助方法

    /// <summary>
    /// 验证操作频率限制
    /// </summary>
    private Task<bool> ValidateActionRateAsync(Guid playerId)
    {
        var now = DateTime.UtcNow;
        
        if (_lastActionTime.TryGetValue(playerId, out var lastTime))
        {
            var timeSinceLastAction = now - lastTime;
            if (timeSinceLastAction.TotalMilliseconds < ACTION_COOLDOWN_MS)
            {
                return Task.FromResult(false);
            }
        }
        
        _lastActionTime[playerId] = now;
        return Task.FromResult(true);
    }

    /// <summary>
    /// 验证移动合法性
    /// </summary>
    private async Task<ValidationResult> ValidateMoveAsync(Guid gameId, Guid playerId, MoveCommand moveCommand)
    {
        var result = new ValidationResult();
        
        // 验证速度
        if (moveCommand.Speed > MAX_MOVE_SPEED)
        {
            result.Errors.Add($"移动速度过快，最大允许速度: {MAX_MOVE_SPEED}");
        }
        
        // 验证位置边界
        if (moveCommand.NewPosition.X < 0 || moveCommand.NewPosition.Y < 0 ||
            moveCommand.NewPosition.X > 1000 || moveCommand.NewPosition.Y > 1000)
        {
            result.Errors.Add("目标位置超出地图边界");
        }
        
        result.IsValid = result.Errors.Count == 0;
        return await Task.FromResult(result);
    }

    /// <summary>
    /// 验证攻击合法性
    /// </summary>
    private async Task<ValidationResult> ValidateAttackAsync(Guid gameId, Guid attackerId, AttackCommand attackCommand)
    {
        var result = new ValidationResult();
        
        // 验证伤害范围
        if (attackCommand.Damage < MIN_ATTACK_DAMAGE || attackCommand.Damage > MAX_ATTACK_DAMAGE)
        {
            result.Errors.Add($"攻击伤害超出允许范围: {MIN_ATTACK_DAMAGE}-{MAX_ATTACK_DAMAGE}");
        }
        
        // 验证目标存在性（如果指定了目标玩家）
        if (attackCommand.TargetPlayerId.HasValue)
        {
            var targetState = await _playerStateService.GetPlayerStateAsync(gameId, attackCommand.TargetPlayerId.Value);
            if (targetState == null || targetState.State == PlayerDrawingState.Dead)
            {
                result.Errors.Add("攻击目标不存在或已死亡");
            }
        }
        
        result.IsValid = result.Errors.Count == 0;
        return result;
    }

    /// <summary>
    /// 检查移动碰撞
    /// </summary>
    private async Task CheckMoveCollisionsAsync(Guid gameId, Guid playerId, Position newPosition, List<GameEvent> events)
    {
        // 简化实现：获取当前玩家状态来检查轨迹碰撞
        var playerState = await _playerStateService.GetPlayerStateAsync(gameId, playerId);
        if (playerState == null) return;
        
        var fromPosition = playerState.CurrentPosition;
        
        // 检查与其他玩家的轨迹碰撞
        var collision = await _collisionDetectionService.CheckTrailCollisionAsync(
            gameId, playerId, fromPosition, newPosition, playerState.State == PlayerDrawingState.Drawing);
            
        if (collision.HasCollision)
        {
            events.Add(new GameEvent
            {
                EventType = "trail_collision",
                PlayerId = playerId,
                Description = "玩家移动时发生轨迹碰撞",
                Timestamp = DateTime.UtcNow,
                Data = new Dictionary<string, object> 
                { 
                    ["collision_type"] = collision.CollisionType.ToString(),
                    ["collision_point"] = collision.CollisionPoint
                }
            });
        }
        
        // 检查道具收集
        var nearbyItems = await GetNearbyItemsAsync(gameId, newPosition);
        if (nearbyItems.Any())
        {
            events.Add(new GameEvent
            {
                EventType = "near_items",
                PlayerId = playerId,
                Description = "玩家移动到道具附近",
                Timestamp = DateTime.UtcNow,
                Data = new Dictionary<string, object> { ["nearby_items"] = nearbyItems.Count }
            });
        }
    }

    /// <summary>
    /// 处理对玩家的攻击
    /// </summary>
    private async Task<float> ProcessPlayerAttackAsync(Guid gameId, Guid attackerId, Guid targetId, AttackCommand attackCommand, List<GameEvent> events)
    {
        var damage = Math.Max(MIN_ATTACK_DAMAGE, Math.Min(attackCommand.Damage, MAX_ATTACK_DAMAGE));
        
        // 简化实现：直接处理玩家死亡（在实际游戏中可能需要生命值系统）
        var deathResult = await _playerStateService.HandlePlayerDeathAsync(gameId, targetId, "攻击伤害", attackerId);
        
        if (deathResult.Success)
        {
            events.Add(new GameEvent
            {
                EventType = "player_attacked",
                PlayerId = attackerId,
                Description = $"对玩家 {targetId} 造成致命攻击",
                Timestamp = DateTime.UtcNow,
                Data = new Dictionary<string, object> 
                { 
                    ["target_id"] = targetId,
                    ["damage"] = damage,
                    ["attack_type"] = attackCommand.AttackType,
                    ["player_died"] = deathResult.Success
                }
            });
            
            return damage;
        }
        
        return 0;
    }

    /// <summary>
    /// 处理区域攻击
    /// </summary>
    private async Task<float> ProcessAreaAttackAsync(Guid gameId, Guid attackerId, Position targetPosition, AttackCommand attackCommand, List<GameEvent> events, List<Guid> affectedPlayers)
    {
        var totalDamage = 0f;
        var attackRadius = 100f; // 区域攻击半径
        
        var allPlayers = await _playerStateService.GetAllPlayerStatesAsync(gameId);
        foreach (var player in allPlayers)
        {
            if (player.PlayerId == attackerId || player.State == PlayerDrawingState.Dead)
                continue;
                
            var distance = CalculateDistance(player.CurrentPosition, targetPosition);
            if (distance <= attackRadius)
            {
                var damage = Math.Max(MIN_ATTACK_DAMAGE, attackCommand.Damage * (1 - distance / attackRadius));
                var deathResult = await _playerStateService.HandlePlayerDeathAsync(gameId, player.PlayerId, "区域攻击", attackerId);
                
                if (deathResult.Success)
                {
                    totalDamage += damage;
                    affectedPlayers.Add(player.PlayerId);
                }
            }
        }
        
        if (totalDamage > 0)
        {
            events.Add(new GameEvent
            {
                EventType = "area_attack",
                PlayerId = attackerId,
                Description = $"区域攻击影响了 {affectedPlayers.Count} 个玩家",
                Timestamp = DateTime.UtcNow,
                Data = new Dictionary<string, object> 
                { 
                    ["total_damage"] = totalDamage,
                    ["affected_count"] = affectedPlayers.Count,
                    ["attack_radius"] = attackRadius
                }
            });
        }
        
        return totalDamage;
    }

    /// <summary>
    /// 获取附近的物品
    /// </summary>
    private async Task<List<PowerUpInstance>> GetNearbyItemsAsync(Guid gameId, Position position)
    {
        var allItems = await _powerUpService.GetMapPowerUpsAsync(gameId);
        var nearbyItems = new List<PowerUpInstance>();
        
        foreach (var item in allItems)
        {
            var distance = CalculateDistance(position, item.Position);
            if (distance <= 30f) // 30单位收集范围
            {
                nearbyItems.Add(item);
            }
        }
        
        return nearbyItems;
    }

    /// <summary>
    /// 获取可用技能列表
    /// </summary>
    private async Task<List<SkillInfo>> GetAvailableSkillsAsync(Guid gameId, Guid playerId)
    {
        // 简化实现，返回基本技能
        return await Task.FromResult(new List<SkillInfo>
        {
            new SkillInfo { SkillId = "speed_boost", Name = "速度提升", Type = "buff" },
            new SkillInfo { SkillId = "shield", Name = "护盾", Type = "defense" },
            new SkillInfo { SkillId = "teleport", Name = "传送", Type = "movement" }
        });
    }

    /// <summary>
    /// 获取技能冷却时间
    /// </summary>
    private TimeSpan GetSkillCooldown(string skillId)
    {
        return skillId switch
        {
            "speed_boost" => TimeSpan.FromSeconds(30),
            "shield" => TimeSpan.FromSeconds(45),
            "teleport" => TimeSpan.FromSeconds(60),
            _ => TimeSpan.FromSeconds(10)
        };
    }

    /// <summary>
    /// 计算两点间距离
    /// </summary>
    private float CalculateDistance(Position pos1, Position pos2)
    {
        var dx = pos1.X - pos2.X;
        var dy = pos1.Y - pos2.Y;
        return (float)Math.Sqrt(dx * dx + dy * dy);
    }

    #region 预测辅助方法

    /// <summary>
    /// 预测移动结果
    /// </summary>
    private async Task PredictMoveResult(Guid gameId, PlayerGameState playerState, MoveCommand moveCommand, 
        ActionPredictionResult prediction, List<string> effects, List<string> risks, Dictionary<string, object> changes)
    {
        prediction.CanExecute = playerState.State != PlayerDrawingState.Dead;
        prediction.SuccessProbability = prediction.CanExecute ? 0.95f : 0;
        
        if (prediction.CanExecute)
        {
            effects.Add("玩家位置将更新");
            changes["new_position"] = new { moveCommand.NewPosition.X, moveCommand.NewPosition.Y };
            
            // 检查移动风险
            var nearbyPlayers = await GetNearbyPlayersAsync(gameId, moveCommand.NewPosition);
            if (nearbyPlayers.Any())
            {
                risks.Add("移动到敌对玩家附近，可能遭受攻击");
                prediction.SuccessProbability *= 0.8f;
            }
        }
        else
        {
            risks.Add("玩家已死亡，无法移动");
        }
    }

    /// <summary>
    /// 预测攻击结果
    /// </summary>
    private async Task PredictAttackResult(Guid gameId, PlayerGameState playerState, AttackCommand attackCommand, 
        ActionPredictionResult prediction, List<string> effects, List<string> risks, Dictionary<string, object> changes)
    {
        prediction.CanExecute = playerState.State != PlayerDrawingState.Dead;
        prediction.SuccessProbability = prediction.CanExecute ? 0.7f : 0;
        
        if (prediction.CanExecute && attackCommand.TargetPlayerId.HasValue)
        {
            var target = await _playerStateService.GetPlayerStateAsync(gameId, attackCommand.TargetPlayerId.Value);
            if (target != null && target.State != PlayerDrawingState.Dead)
            {
                effects.Add($"将对目标造成攻击");
                changes["damage_dealt"] = attackCommand.Damage;
                // 简化实现：假设攻击会导致目标死亡
                changes["target_defeated"] = true;
                
                effects.Add("目标玩家将被击败");
                changes["target_defeated"] = true;
            }
            else
            {
                risks.Add("攻击目标不存在或已死亡");
                prediction.SuccessProbability = 0;
            }
        }
        else if (!prediction.CanExecute)
        {
            risks.Add("玩家已死亡，无法攻击");
        }
    }

    /// <summary>
    /// 预测技能结果
    /// </summary>
    private Task PredictSkillResult(Guid gameId, PlayerGameState playerState, SkillUseCommand skillCommand, 
        ActionPredictionResult prediction, List<string> effects, List<string> risks, Dictionary<string, object> changes)
    {
        var cooldownKey = $"{playerState.PlayerId}_{skillCommand.SkillId}";
        var hasCD = _cooldownTracker.ContainsKey(cooldownKey) && _cooldownTracker[cooldownKey] > TimeSpan.Zero;
        
        prediction.CanExecute = playerState.State != PlayerDrawingState.Dead && !hasCD;
        prediction.SuccessProbability = prediction.CanExecute ? 0.9f : 0;
        
        if (prediction.CanExecute)
        {
            effects.Add($"将使用技能: {skillCommand.SkillId}");
            changes["skill_used"] = skillCommand.SkillId;
            changes["cooldown_applied"] = GetSkillCooldown(skillCommand.SkillId).TotalSeconds;
            
            // 基于技能类型添加特定效果
            switch (skillCommand.SkillId)
            {
                case "speed_boost":
                    effects.Add("移动速度将临时提升");
                    break;
                case "shield":
                    effects.Add("将获得临时护盾");
                    break;
                case "teleport":
                    effects.Add("将传送到指定位置");
                    risks.Add("传送位置可能不安全");
                    break;
            }
        }
        else
        {
            if (playerState.State == PlayerDrawingState.Dead)
                risks.Add("玩家已死亡，无法使用技能");
            if (hasCD)
                risks.Add("技能正在冷却中");
        }
        
        return Task.CompletedTask;
    }

    /// <summary>
    /// 预测领土占领结果
    /// </summary>
    private async Task PredictTerritoryResult(Guid gameId, PlayerGameState playerState, TerritoryClaimCommand territoryCommand, 
        ActionPredictionResult prediction, List<string> effects, List<string> risks, Dictionary<string, object> changes)
    {
        prediction.CanExecute = playerState.State != PlayerDrawingState.Dead;
        prediction.SuccessProbability = prediction.CanExecute ? 0.8f : 0;
        
        if (prediction.CanExecute)
        {
            var predictedArea = (float)Math.PI * territoryCommand.Radius * territoryCommand.Radius;
            effects.Add($"将占领面积约为 {predictedArea:F1} 的领土");
            changes["territory_gained"] = predictedArea;
            changes["bonus_score"] = (int)(predictedArea * 10);
            
            // 检查领土冲突风险
            var conflictRisk = await CheckTerritoryConflictRiskAsync(gameId, territoryCommand.Position, territoryCommand.Radius);
            if (conflictRisk > 0)
            {
                risks.Add("占领区域与其他玩家领土重叠，可能引发冲突");
                prediction.SuccessProbability *= (1 - conflictRisk);
            }
        }
        else
        {
            risks.Add("玩家已死亡，无法占领领土");
        }
    }

    /// <summary>
    /// 获取附近的玩家
    /// </summary>
    private async Task<List<PlayerGameState>> GetNearbyPlayersAsync(Guid gameId, Position position)
    {
        var allPlayers = await _playerStateService.GetAllPlayerStatesAsync(gameId);
        return allPlayers.Where(p => p.State != PlayerDrawingState.Dead && 
                               CalculateDistance(p.CurrentPosition, position) <= 50f).ToList();
    }

    /// <summary>
    /// 检查领土冲突风险
    /// </summary>
    private async Task<float> CheckTerritoryConflictRiskAsync(Guid gameId, Position position, float radius)
    {
        // 简化实现：检查是否与现有领土重叠
        var allPlayers = await _playerStateService.GetAllPlayerStatesAsync(gameId);
        var conflictCount = 0;
        
        foreach (var player in allPlayers)
        {
            foreach (var territory in player.OwnedTerritories)
            {
                // 简化实现：假设每个领土都有一个中心点和半径
                if (territory.Boundary.Any())
                {
                    var territoryCenter = new Position
                    {
                        X = territory.Boundary.Average(p => p.X),
                        Y = territory.Boundary.Average(p => p.Y)
                    };
                    var territoryRadius = Math.Sqrt(territory.Area / Math.PI); // 假设为圆形领土
                    
                    var distance = CalculateDistance(position, territoryCenter);
                    if (distance < radius + territoryRadius)
                    {
                        conflictCount++;
                    }
                }
            }
        }
        
        return Math.Min(conflictCount * 0.2f, 0.8f); // 最多80%的冲突风险
    }

    /// <summary>
    /// 验证位置是否有效
    /// </summary>
    private bool IsPositionValid(Guid gameId, Position position)
    {
        // 简化实现：检查是否在地图边界内
        return position.X >= 0 && position.X <= 1000 && 
               position.Y >= 0 && position.Y <= 1000;
    }

    /// <summary>
    /// 应用延迟补偿
    /// </summary>
    private Position ApplyLatencyCompensation(Position originalPosition, float latencyMs)
    {
        // 简化实现：基于延迟调整位置
        var compensationFactor = Math.Min(latencyMs / 1000f, 0.1f); // 最大10%补偿
        return new Position
        {
            X = originalPosition.X,
            Y = originalPosition.Y
        };
    }

    #endregion

    #endregion
}

/// <summary>
/// 验证结果类
/// </summary>
public class ValidationResult
{
    public bool IsValid { get; set; } = true;
    public List<string> Errors { get; set; } = new();
}

/// <summary>
/// 技能信息类
/// </summary>
public class SkillInfo
{
    public string SkillId { get; set; } = string.Empty;
    public string Name { get; set; } = string.Empty;
    public string Type { get; set; } = string.Empty;
}
